/**********************************************
** @Author: phy
** @Date:   2017-12-12 14:17:37
** @Last Modified by:   phy
** @Last Modified time: 2017-09-17 10:12:06
***********************************************/

package libs

import (
	"crypto/md5"
	"fmt"
	"math/rand"
	"regexp"
	"time"
	"github.com/astaxie/beego"
	"strconv"
)

var emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")


func GetEnCodeByMd5(str string) (string) {

	//方法一
	data := []byte(str)
	has := md5.Sum(data)
	md5str1 := fmt.Sprintf("%x", has) //将[]byte转成16进制

	return md5str1
}


func SizeFormat(size float64) string {
	units := []string{"Byte", "KB", "MB", "GB", "TB"}
	n := 0
	for size > 1024 {
		size /= 1024
		n += 1
	}

	return fmt.Sprintf("%.2f %s", size, units[n])
}

func IsEmail(b []byte) bool {
	return emailPattern.Match(b)
}

func Password(len int, pwdO string) (pwd string, salt string) {
	salt = GetRandomString(4)
	defaultPwd := "admin123456"
	if pwdO != "" {
		defaultPwd = pwdO
	}
	pwd = GetEnCodeByMd5(defaultPwd + salt)
	return pwd, salt
}

// 生成32位MD5
// func MD5(text string) string{
//    ctx := md5.New()
//    ctx.Write([]byte(text))
//    return hex.EncodeToString(ctx.Sum(nil))
// }

//生成随机字符串
func GetRandomString(lens int) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < lens; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

func GetStringOk(str,strOk string) ([]interface{}) {
	bytes := []byte(str)
	result := []byte{}
	GetStr := make([]interface{}, 0)
	for i := 0; i < len(bytes); i++ {
		var tmp string = string(bytes[i])
		if tmp == strOk{
			strtmp := string(result);
			if strtmp != ""{
				GetStr = append(GetStr,strtmp);
			}
			result = []byte{}
			continue;
		}
		result  = append(result, bytes[i])
	}
	return GetStr;
}

func  GetUnixZeroTime() int64 {
	notTime := time.Now()
	iYerr := notTime.Year()
	iMonth := notTime.Month();
	iDay := notTime.Day()

	timestr := fmt.Sprintf("%04d-%02d-%02d", iYerr,iMonth,iDay)
	return GetStringTimeToUnix(timestr, "Y-m-d")
}

func  GetYesterdayUnixZeroTime() int64 {
	notTime := time.Now()
	iYerr := notTime.Year()
	iMonth := notTime.Month();
	iDay := notTime.Day()

	timestr := fmt.Sprintf("%04d-%02d-%02d", iYerr,iMonth,iDay)
	return (GetStringTimeToUnix(timestr, "Y-m-d") - 86400);
}
func GetTaxRateToSring(sum,count int64)string{
	var tmpRate float64 = 0.00;
	if count == 0 {
		count = 1;
	}

	tmpRate = float64(sum)/float64(count)

	return fmt.Sprintf("%.2f", tmpRate)
}
/*
 "Y-m-d"
 "Y-m-d H:i:s"
 "YYYYmmdd"
*/
func GetStringTimeToUnix(tmieString,Formatstring string) int64{
	tmptm,err := beego.DateParse(tmieString,Formatstring)
	if(err != nil){
		return GetUnixZeroTime();
	}
	return tmptm.Unix();
}
func GetCurSysTmeTimeToUnix() int64{

	notTime := time.Now()
	iYerr := notTime.Year()
	iMonth := notTime.Month();
	iDay := notTime.Day()
	iHour := notTime.Hour()
	iMinute := notTime.Minute();
	iSecond := notTime.Second();
	timestr := fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d", iYerr,iMonth,iDay,iHour,iMinute,iSecond)
	return GetStringTimeToUnix(timestr, "Y-m-d H:i:s")
}

func GetDateNowString()string {
	return beego.Date(time.Unix(GetCurSysTmeTimeToUnix(), 0), "Y-m-d H:i:s")
}
/*
 "Y-m-d"
 "Y-m-d H:i:s"
 "Ymd"
*/
func GetDateToString(datastr, datafomat,GetFormat string)string {
	return beego.Date(time.Unix(GetStringTimeToUnix(datastr,datafomat), 0), GetFormat)
}
func GetDateToInt(datastr, datafomat,GetFormat string)(int,error) {
	 str := beego.Date(time.Unix(GetStringTimeToUnix(datastr,datafomat), 0), GetFormat)
	 return strconv.Atoi(str)  
}

func RandInt64(min, max int64) int64 { 
	tmp:= min; 
	if(min > max){
		min = max;
		max = tmp;	
	}   
    r := rand.New(rand.NewSource(time.Now().UnixNano()))  
    return r.Int63n(max-min) + min  
} 